package com.ztom.v2;

/**
 * @author ZhangTao
 */
public class Code26LinkedListCycle2 {
    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        // 快慢指针
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            // 第一次相遇
            if (fast == slow) {
                // fast 回到 head, 降速
                fast = head;
                while (fast != null && slow != null) {
                    if (fast == slow) {
                        return fast;
                    }
                    slow = slow.next;
                    fast = fast.next;
                }
            }
        }
        return null;
    }
}
